package com.fh.module_main.viewmodel

import android.os.Looper
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.fh.lib_base.base.BaseBean
import com.fh.lib_base.base.BaseViewModel
import com.fh.lib_base.base.MyApplication
import com.fh.lib_base.data.DataRepository
import com.fh.lib_base.data.bean.BannerBean
import com.fh.lib_base.extension.ApiSubscriberHelper
import com.fh.lib_base.util.RxThreadHelper
import com.fh.lib_base.data.bean.CityBean
import com.fh.lib_base.data.bean.CityItems
import com.fh.lib_base.data.bean.CitySortBean
import com.fh.module_main.data.LocationBean
import com.github.stuxuhai.jpinyin.PinyinException
import com.github.stuxuhai.jpinyin.PinyinFormat
import com.github.stuxuhai.jpinyin.PinyinHelper
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import java.util.*
import kotlin.collections.ArrayList

class SearchFragmentViewModel(application: MyApplication, dataRepository: DataRepository) :
    BaseViewModel<DataRepository>(application, dataRepository),TencentLocationListener  {

    //首页轮播图数据
    var bannerData: MutableLiveData<List<BannerBean>> = MutableLiveData()
    //定位信息
    var locationLiveData: MutableLiveData<LocationBean> = MutableLiveData()
    //获取热门城市
    var hotCityData: MutableLiveData<ArrayList<CityBean>> = MutableLiveData()
    //获取所有城市
    var allCityListData: MutableLiveData<ArrayList<CityItems>> = MutableLiveData()

    //城市搜索结果
    var citySearchResultListData: MutableLiveData<ArrayList<CityBean>> = MutableLiveData()

    //第一次加载之后缓存的数据
    private var cacheCityList = ArrayList<CityItems>()
    private var tempCityList = ArrayList<CityItems>()


    fun getSearchBannerData(){
        model.apply {
            getSearchBannerData().compose(RxThreadHelper.rxSchedulerHelper(this@SearchFragmentViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<List<BannerBean>>>() {
                    override fun onResult(t: BaseBean<List<BannerBean>>) {
                        dismissLoading()
                        if (t.errorCode == 0) {
                            if(t.data != null){
                               bannerData.value = t.data
                               showSuccessToast("轮播图获取成功")
                            }
                        }
                    }
                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showNormalToast(msg)
                    }
                })
        }
    }
    //单点定位
    fun getCurrentLocation(){
        var mLocationManager = TencentLocationManager.getInstance(getApplication())
        mLocationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper())
    }
    //用于接收定位结果
    override fun onLocationChanged(location: TencentLocation?, error: Int, reason: String?) {
        Log.i("info","错误代码:"+error)
        if(location != null && error != 2){
            locationLiveData.value = LocationBean(location!!.city,location!!.district,location!!.street)
        }
    }
    //用于接收GPS、WiFi、Cell状态码
    override fun onStatusUpdate(name: String?, status: Int, desc: String?) {
    }
    //获取热门城市
    fun getHotCityListData(){
        model.apply {
            getHotCityListData().compose(RxThreadHelper.rxSchedulerHelper(this@SearchFragmentViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<ArrayList<CityBean>>>() {
                    override fun onResult(t: BaseBean<ArrayList<CityBean>>) {
                        dismissLoading()
                        if (t.errorCode == 0) {
                            if(t.data != null){
                                hotCityData.value = t.data
                            }
                        }
                    }
                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showNormalToast(msg)
                    }
                })
        }
    }
    //获取所有城市
    fun getAllCityListData(){
        model.apply {
            getAllCityListData().compose(RxThreadHelper.rxSchedulerHelper(this@SearchFragmentViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<ArrayList<CitySortBean>>>() {
                    override fun onResult(t: BaseBean<ArrayList<CitySortBean>>) {
                        dismissLoading()
                        if (t.errorCode == 0) {
                            if(t.data != null){
                                for (list in t.data!!){
                                    for (item in list.subItems){
//                                        Log.i("info",item.toString())
                                        tempCityList.add(item)
                                    }
                                }
                                allCityListData.value = bindData(tempCityList)
                            }
                        }
                    }
                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showNormalToast(msg)
                    }
                })
        }
    }
    //获取城市搜索结果
    fun getCitySearchResultListData(keyword: String){
        model.apply {
            getCitySearchResultListData(keyword).compose(RxThreadHelper.rxSchedulerHelper(this@SearchFragmentViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<ArrayList<CityBean>>>() {
                    override fun onResult(t: BaseBean<ArrayList<CityBean>>) {
                        dismissLoading()
                        if (t.errorCode == 0) {
                            if(t.data != null){
                                citySearchResultListData.value = t.data
                            }
                        }
                    }
                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showNormalToast(msg)
                    }
                })
        }
    }
    /**
     * 给View绑定数据
     *
     * @param allCity 所有城市列表
     */
    fun bindData(allCity: ArrayList<CityItems>): ArrayList<CityItems> {
        if (allCity != null) {
            for (cityModel in allCity) {
                try {
                    var pingYin = PinyinHelper.convertToPinyinString(cityModel.name," ",PinyinFormat.WITHOUT_TONE)
                    cacheCityList.add(CityItems(cityModel.name, pingYin,pingYin.substring(0, 1)))
                } catch (e: PinyinException) {
                    e.printStackTrace();
                }
            }
            //排序
            Collections.sort(cacheCityList,object: Comparator<CityItems> {
                override fun compare(o1: CityItems, o2: CityItems): Int {
                    return o1.sortName.compareTo(o2.sortName)
                }
            })
            allCityListData.value = cacheCityList
        }
        return allCityListData.value!!;
    }

}

